library(foreign)
library(pander)

representativeness.function <- function(experiment) {
  data <- read.dta(experiment) #Read in data
  representativeness.vars <- unique(unlist(strsplit(as.character(subset(master.sheet, master.sheet$Data == experiment, 
                                                                 c(xvars, dv_t0, votechoice_t0))), " ")))
  #Create the list of covariates using xvars from the experiment, t0 DV (factor), and t0 vote choice
  representativeness.vars <- c(representativeness.vars, "t0_pid", "t0_identify_afam", "t0_identify_poc")
  #Add in PID, AfAm, and Person of Color (POC). These variable names are the same in all experiments.
  representativeness.vars <- gsub('c\\(\\"', "", representativeness.vars)
  representativeness.vars <- gsub('\n', "", representativeness.vars)
  representativeness.vars <- gsub('\"', "", representativeness.vars)
  representativeness.vars <- gsub(',', "", representativeness.vars)
  representativeness.vars <- gsub('\\)', "", representativeness.vars)
  representativeness.vars <- unique(representativeness.vars) #De-dup variable names.
  x.canvassed <- data[,representativeness.vars] #Create data of everyone canvassed.
  x.canvassed <- as.matrix(x.canvassed, dimnames = list(NULL, names(x)))
  x.respondent.t1 <- subset(data, data$respondent_t1 == 1, representativeness.vars) #Create data of post-survey respondents.
  x.respondent.t1 <- as.matrix(x.respondent.t1, dimnames = list(NULL, names(x)))
  canvassed.means <- data.frame(t(colMeans(x.canvassed))) #Calculate means.
  canvassed.means$n <- nrow(x.canvassed)
  respondent.means <- data.frame(t(colMeans(x.respondent.t1)))
  respondent.means$n <- nrow(x.respondent.t1)
  means <- rbind(canvassed.means, respondent.means)
  row.names(means) <- c("Canvassed", "Post-Canvass Survey Respondent")
  means <- t(means)
  #Print
  panderOptions('big.mark', ',')
  panderOptions('table.style','rmarkdown')
  panderOptions('table.alignment.default','right')
  panderOptions('table.alignment.rownames','left')
  panderOptions('digits','2')
  panderOptions('table.caption.prefix','')
  set.caption("**Representativeness of Experiment at Each Stage.** Each cell reports the average value of a different covariate at each stage. t0_pid is the standard 7-point party ID variable, with higher values for stronger Democrats. t0_identify_afam is a binary variable, coded as 1 if the survey responded identified as African American. t0_identify_poc is a similar binary variable, but for any non-white person of color. Vote choice variables are typically 7-point scales, with higher values for the Democrat. Favorability variables are 7-pint scales, with higher values more favorable. Finally, n refers to the number of individals at each stage.")
  pander(means, split.tables = 110)
}
